﻿//cookie List
//候诊人数
var System_Wait_Num = "sys_wait_num_nurse";
//已就诊人数
var System_After_Num = "sys_accept_num_nurse";
//过号人数
var System_Accept_Num = "sys_accept_num_nurse";

//排队叫号
var PDJH = QueueCallUrl;
//系统权限
//var SystemLimitUrl = SystemLimitUrl;
//STS
var STSUrl = TriageUrl;


var mDeviceType = "";
var mHospitalId = "";
var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");

//登录用户ID
function getLoginUserId() {

    if (isTest) {
        return '9c51b1775c314a57816d89701a29e5df';
    }
    return getCookie('userId');
}

//分诊台ID
function getDeviceId() {
    if (isTest) {
        return '11ef8de08c8a4470b27c6306160e1bef';
    }
    return getCookie('deviceId');
}

//医院ID
function getHospitalId() {

    if (isTest) {
        return '4e66fabafd944e458dc259ce890c31f3';
    }
    return getCookie('hospitalId');

}

//获取设备IP 赋值
function setCookie(k, v) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 30);
    document.cookie = k + "=" + escape(v) + ((30 == null) ? "" : ";expires=" + exdate.toGMTString());
}

//获取cookie参数
function getCookie(key) {
    var arr, reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        //console.log(arr[2]);
        return (arr[2]);
    }
    else
        return null;
}


//最小化
function FormMin() {
    my_cefsharp.CefSharp_MainForm_Min();
}

//关闭
function FormClose() {
    if (confirm("确认关闭程序吗？")) {
        my_cefsharp.CefSharp_MainForm_Close();
    }
}

function loginClose() {
    my_cefsharp.CefSharp_MainForm_Close();
}

//全屏
function FormMax() {
    my_cefsharp.CefSharp_MainForm_Max();
}

//登录成功，将悬浮窗体调出
function LoginSuccess(userName) {
    my_cefsharp.CefSharp_Login_Success(userName);
}

//医生停诊
function Doctor_Write_Off(deptName, doctorRoomName, doctorName, queueName) {
    layer.alert(deptName + " " + doctorRoomName + " " + doctorName + " " + queueName + "\n已停诊，请妥善安置其候诊患者", {icon: 0});
}

//更新分诊台系统候诊患者数量  end
function Update_System_Wait_End_Num(sysId, waitnum, treatedNum) {
    var systemIdSelect = allOrSingleSystemIds();
    if (sysId != null) {
        setCookie(sysId, waitnum);
        if (systemIdSelect == sysId) {
            $("#m_span_hz").html(waitnum);
            $("#m_span_yjz").html(treatedNum);
        }
    }
}

//分诊台点击过号召回时,发送分诊台系统的候诊数目，过号数目变化
function Update_System_Wait_Pass_Num(sysId, waitNum, overFlowPatient) {
    var systemIdSelect = allOrSingleSystemIds();
    if (sysId != null) {
        setCookie(sysId, waitNum);
        if (systemIdSelect == sysId) {
            $("#m_span_hz").html(waitNum);
            $("#m_span_gh").html(overFlowPatient);
        }
    }
}


//重置全部候诊
function Reset_System_Wait_Num_Nurse(sysId, waitnum) {
    var systemIdSelect = allOrSingleSystemIds();
    if (sysId != null) {
        setCookie(sysId, waitnum);
        if (systemIdSelect == sysId) {
            $("#m_span_hz").html(waitnum);
        }
    }
}

//重置全部过号
function Reset_System_After_Num_Nurse(sysId, afternum) {
    var systemIdSelect = allOrSingleSystemIds();
    if (sysId != null) {
        setCookie(sysId, afternum);
        if (systemIdSelect == sysId) {
            $("#m_span_gh").html(afternum);
        }
    }
}

//重置全部已就诊
function Reset_System_Accept_Num_Nurse(sysId, acceptnum) {
    var systemIdSelect = allOrSingleSystemIds();
    if (sysId != null) {
        setCookie(sysId, acceptnum);
        if (systemIdSelect == sysId) {
            $("#m_span_yjz").html(acceptnum);
        }
    }
}

//更新队列在线状态
function Reset_STS_Update_Queue_Status(sysId, queueId, onLineStatus, listType) {
    if (queueId) {
        $("#"+ queueId + "_text").siblings('span.mui-status').removeAttr('class').addClass('mui-status queueStatus-'+onLineStatus);
    }
}

//重置队列候诊
function Reset_Queue_Wait_Num_Nurse(queueId, waitnum) {
    if(queueId&&queueId!=''){
        $('#qid_'+queueId).find('.waitCount').text(waitnum);
    }
};

//重置队列过号
function Reset_Queue_After_Num_Nurse(queueId, afternum) {
    if(queueId&&queueId!=''){
        $('#qid_'+queueId).find('.overCount').text(afternum);
    }
}

//重置队列已就诊
function Reset_Queue_Accept_Num_Nurse(queueId, acceptnum) {
    if(queueId&&queueId!=''){
        $('#qid_'+queueId).find('.endCount').text(acceptnum);
    }
}
//重置队列已就诊
function Reset_Queue_NoSign_Num_Nurse(queueId, count) {
    if(queueId&&queueId!=''){
        $('#qid_'+queueId).find('.noSignCount').text(count);
    }
}

//重置分诊台队列的候诊与已就诊人数:
function Reset_Queue_Wait_End_Num_Nurse(queueid, waitnum, endnum) {
    if(queueid&&queueid!=''){
        $('#qid_'+queueid).find('.waitCount').text(waitnum);
        $('#qid_'+queueid).find('.endCount').text(endnum);
    }

}

//分诊台点击过号召回时,发送分诊台队列的候诊数目，过号数目变化
function Reset_Queue_Wait_Pass_Num_Nurse(queueid, waitNum, overFlowPatientNum) {
    if(queueid&&queueid!=''){
        $('#qid_'+queueid).find('.waitCount').text(waitNum);
        $('#qid_'+queueid).find('.overCount').text(overFlowPatientNum);
    }
}


//设置cookie参数
function setLocalDeviceCookie() {

    //获取设备IP 回调
    my_cefsharp.Get_CallingOrTriage_IPAndMac_Cef(SetLocalDevIp_Mac);
    //获取设备MAC 回调
    my_cefsharp.Get_CallingOrTriage_Mac_Cef(SetLoaclDevMac)
    //获得设备ID 回调
    my_cefsharp.Get_DeviceType_Cef(SetDeviceType);
    //获得LoginToken 回调
    my_cefsharp.Get_LoginTocken_Cef(SetLoginToken);
    //获得医院ID 回调
    my_cefsharp.Get_HospitalId_Cef(SetHospitalId);
    //获得叫号器或者分诊台ID -回调
    my_cefsharp.Get_CallingOrTriage_ID_Cef(SetCallingOrTriageId);
    //获得用户名
    my_cefsharp.Get_LoginUserName_cef(SetLoginName);
}

//获取cookie参数
function getLocalDeviceCookie(key) {
    var arr, reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        //console.log(arr[2]);
        return (arr[2]);
    }
    else
        return null;
}

//设置设备IP 赋值
function SetLocalDevIp_Mac(s, m) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 30);
    document.cookie = "LOCAL_DEV_IP" + "=" + escape(s) + ((30 == null) ? "" : ";expires=" + exdate.toGMTString());
    document.cookie = "LOCAL_DEV_MAC" + "=" + escape(m) + ((30 == null) ? "" : ";expires=" + exdate.toGMTString());
}

//设置用户名
function SetLoginName(s) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 30);
    document.cookie = "LOCAL_DEV_LOGINNAME" + "=" + escape(s) + ((30 == null) ? "" : ";expires=" + exdate.toGMTString());
}

//设置设备MAC
function SetLoaclDevMac(s) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 30);
    document.cookie = "LOCAL_DEV_MAC" + "=" + escape(s) + ((30 == null) ? "" : ";expires=" + exdate.toGMTString());
}

//设置设备ID
function SetDeviceType(s) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 30);
    document.cookie = "LOCAL_DEV_TYPE" + "=" + escape(s) + ((30 == null) ? "" : ";expires=" + exdate.toGMTString());
}

//设置LoginToken
function SetLoginToken(s) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 30);
    document.cookie = "LOGIN_TOKEN" + "=" + escape(s) + ((30 == null) ? "" : ";expires=" + exdate.toGMTString());
    my_cefsharp.Set_LoginToken_Cef(s);
}

//设置医院ID
function SetHospitalId(s) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 30);
    document.cookie = "HOSPITAL_ID" + "=" + escape(s) + ((30 == null) ? "" : ";expires=" + exdate.toGMTString());
}

//设置叫号器或者分诊台ID
function SetCallingOrTriageId(s) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 30);
    document.cookie = "C_OR_T_ID" + "=" + escape(s) + ((30 == null) ? "" : ";expires=" + exdate.toGMTString());
}

//设置叫号器或者分诊台ID
function SetCallingOrTriage_ID(s, key) {
    my_cefsharp.Set_CallingOrTriage_ID_Cef(s, key);
}

//根据pagekey打开特定界面。
function RedirectByKey(key) {
    my_cefsharp.Open_Page_By_PageKey(key);
}

// 通知csharp做打印操作
function PrintByCSharp(treatCode, htmlText) {
    my_cefsharp.PrintPage(treatCode, htmlText);
}

//获取get参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}

//本周开始
function getWeekStartDate() {
    var Nowdate = new Date();
    var WeekFirstDay = new Date(Nowdate - (Nowdate.getDay() - 1) * 86400000);
    // M = Number(WeekFirstDay.getMonth()) + 1
    // return WeekFirstDay.getFullYear() + "-" + M + "-" + WeekFirstDay.getDate();
    M = Number(WeekFirstDay.getMonth()) + 1;
    //补齐0
    D = WeekFirstDay.getDate();
    if (D >= 0 && D <= 9)  D = "0" + D;
    // console.log(D);

    return WeekFirstDay.getFullYear() + "-" + M + "-" + D;

}

//获得本周的结束
function getWeekEndDate() {
    var Nowdate = new Date();
    var WeekFirstDay = new Date(Nowdate - (Nowdate.getDay() - 1) * 86400000);
    var WeekLastDay = new Date((WeekFirstDay / 1000 + 6 * 86400) * 1000);
    // M = Number(WeekLastDay.getMonth()) + 1
    // return WeekLastDay.getFullYear() + "-" + M + "-" + WeekLastDay.getDate();
    M = Number(WeekLastDay.getMonth()) + 1;
    //补齐0
    D = WeekLastDay.getDate();
    if (D >= 0 && D <= 9)  D = "0" + D;
    // console.log(D);
    return WeekLastDay.getFullYear() + "-" + M + "-" + D;

}

//格式化日期：yyyy-MM-dd
function formatDate(date) {
    var myyear = date.getFullYear();
    var mymonth = date.getMonth() + 1;
    var myweekday = date.getDate();
    if (mymonth < 10) {
        mymonth = "0" + mymonth;
    }
    if (myweekday < 10) {
        myweekday = "0" + myweekday;
    }
    return (myyear + "-" + mymonth + "-" + myweekday);
}

//比较2个时间的大小
function CompareDate(d1, d2) {
    return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
}

//获取今天日期
function showToDay() {
    var Nowdate = new Date();
    M = Number(Nowdate.getMonth()) + 1
    return Nowdate.getFullYear() + "-" + M + "-" + Nowdate.getDate();
}
/** 用不到了，方法名称重复
function getDeptId() {

    var _deptId = "184092d8e1164e09a7a7d467daa040e6";// "2264b5f41af44f3691f419d1f572a0e5";

    //$.ajax({
    //    url: PDJH + "/Triage/getDeptList",
    //    type: 'get',
    //    async: false,
    //    success: function (d) {
    //        console.log("success->" + _deptId);
    //        _deptId = JSON.parse(d).data.deptId;
    //    }, error: function (d) {
    //        console.log("error->" + _deptId);
    //    }
    //});

    return _deptId;
}
 */
//排班模板分辨率
function loadPbTemplateResolution(divId) {

    var queryPbResolutionUrl = ArrangeUrl + "/HsTemplate/queryResolutionList";

    $.ajax({
        url: queryPbResolutionUrl,
        type: 'get',
        success: function (d) {
            // console.log(d);
            if (JSON.parse(d).status == '0') {
                var dataInfo = JSON.parse(d).data;
                var _option = "<option value=''>全部</option>";
                for (var i = 0; i < dataInfo.length; i++) {
                    if (dataInfo[i] == null)
                        continue;
                    _option += "<option value='" + dataInfo[i] + "'>" + dataInfo[i] + "</option>";
                }
                $("#" + divId).html(_option);
            }
        }
    });
}

// 判断是全部还是选中系统
function allOrSingleSystemIds() {
    var systemId = $("#select_call_systemType").val();
    var localSystemId = localStorage["systemId"];
    if (systemId == "全部") {
        if (localSystemId != "" || localSystemId != undefined || localSystemId != null) {
            systemId = localSystemId;
        } else {
            systemId = $("#select_call_systemType").find("option:eq(1)").prop("value");
        }
    } else {
        systemId = $("#select_call_systemType").val();
    }
    return systemId;
}


/**
 * 当修改下拉框时，刷新分诊台右侧区域
 * @param selectedQueueId 选中的队列id
 */
function refreshRightRegionBy_C() {
    var mainheight = $("#d_left").css("height");
    $('#d_right_content').html('<iframe id="patient_tmt_info" scrolling="no" src="./nurse_mgr/patient_tmt_info.html" style="width:100%;border:none;height:100%;"></iframe>');
}


function refreshNoSplitPatientsTableBy_C() {
    notSplitDiaOpt(0);
}

/**
 * 是否显示“预检颜色”按钮，现场报到
 * @returns 预检选项 1 开启  0 关闭
 */
function showIsPretest(systemId) {
    var _isPretestSystemId = 1 + systemId;
    var _noPretestSystemId = 0 + systemId;
    var _isPretest = "";
    if (localStorage.getItem(_isPretestSystemId) != null) {
        _isPretest = localStorage.getItem(_isPretestSystemId);
    } else {
        if (localStorage.getItem(_noPretestSystemId) != null) {
            _isPretest = localStorage.getItem(_noPretestSystemId);
        }
    }
    return _isPretest;
}
/***
 *  数组去重
 *  @param arr
 *  return Array
 * */
function uniqueArr(arr){
    var arr1 = [];
    var obj = {};
    for(var i =0,len=arr.length;i<len;i++){
        if(!obj[arr[i]]){
            arr1.push(arr[i]);
            obj[arr[i]] = 1;
        }
        else{
            obj[arr[i]]++;
        }
    }
    return arr1;
}

/**
 *  这是给C端准备的弹窗
 * */
function alertMsgFromCefsharp(obj) {
    try{
        layer.msg(obj.desc,{icon:obj.icon})
    }catch (e) {
        alert(str)
    }
}

/**
 * 勿扰模式是否开启
 * 默认为关闭状态，开启后主叫方无法呼通此分诊台，且对讲按钮增加勿扰的角标显示
 * 因为多个页面使用，纯在跨页面问题，所以拿出来共用
 */
function isDisableCall(type) {
    if(type){
        $("#notDisturb").show();
    }else{
        $("#notDisturb").hide();
    }
}
function debounce(fn, wait) {
    let timer = null;
    return function() {
        var context = this,
            args = arguments;
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
        timer = setTimeout(() => {
            fn.apply(context, args);
        }, wait);
    };
}
